<template>
    <div class="memberinfo-layout" v-loading="loading">
        <div class="info-back  search-part">
            <el-row :gutter="20">
                <el-col :span="12">
                    <div class="back-icon" @click="back">
                        <i class="fa fa-arrow-left" aria-hidden="true"></i>
                    </div>
                </el-col>
                <el-col :span="10" class="btns">
                    <el-button type="text" class="save red-btn" @click="onSubmit('formInfo')">
                        保存
                    </el-button>
                    <el-button type="text" class="save gray-btn" @click="effect('formInfo')">
                        生效
                    </el-button>
                </el-col>
            </el-row>
        </div>
        <div class="member-info-title">
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="采购信息" name="first">
                    <!--<keep-alive v-if="formInfo.name">-->
                    <div class="member-info-form">
                        <el-form
                          label-width="100px"
                          ref="formInfo"
                          :rules="formInfoRules"
                          :model="formInfo"
                        >
                          <el-form-item label="采购单号:" prop="sn">
                              <el-input v-model="formInfo.sn" :disabled="true"></el-input>
                          </el-form-item>
                          <el-form-item label="业务类型:" prop="biztype">
                              <el-input v-model="formInfo.biztype" placeholder="采购入库" :disabled="true"></el-input>
                          </el-form-item>
                          <el-form-item label="采购方式:">
                              <!--<div class="el-left">-->
                                  <!--<el-select v-model="formInfo.kind_code" placeholder="请选择采购类型">-->
                                      <!--<el-option label="现购" value="10"></el-option>-->
                                      <!--<el-option label="赊购" value="20"></el-option>-->
                                  <!--</el-select>-->
                              <!--</div>-->
                            <div class="el-left">
                             <el-select v-model="value" placeholder="现购" :disabled="isDisabled">
                                 <el-option
                                         v-for="item in options"
                                         :key="item.value"
                                         :label="item.label"
                                         :value="item.value"
                                 >
                                 </el-option>
                             </el-select>
                           </div>
                          </el-form-item>
                          <el-form-item label="总金额:" prop="amount">
                              <el-input v-model="formInfo.amount" :disabled="true"></el-input>
                          </el-form-item>
                          <el-form-item label="经手人:" prop="handerName">
                              <el-input v-model="formInfo.handerName" placeholder="（添加经手人）" :disabled="isDisabled"></el-input>
                          </el-form-item>
                          <el-form-item label="制单人:"  prop="creatorName" >
                              <el-input v-model="formInfo.creatorName" :disabled="true"></el-input>
                          </el-form-item>
                          <el-form-item label="入库日期:" prop="bizdate">
                              <el-input v-model="formInfo.bizdate" :disabled="true"></el-input>
                          </el-form-item>
                          <el-form-item label="备注:" prop="remark" class="member-mark">
                              <el-input type="textarea" v-model="formInfo.remark" :disabled="isDisabled"></el-input>
                          </el-form-item>
                        </el-form>
                    </div>
                    <!--</keep-alive>-->
                </el-tab-pane>
                <el-tab-pane label="商品详情" name="second">
                    <div class="memeber-manage-con" id="myDIV">
                        <waterfall
                                :line-gap="250"
                                :max-line-gap="360"
                                :min-line-gap="220"
                                :fixed-height="true"
                                :watch="items"
                                align="center">
                            <waterfall-slot
                                    :width="250"
                                    :height="220"
                                    :order="index"
                                    v-if="isClose"
                            >
                                <div class="member-layout storage" style="height: 220px;">
                                    <div class="grid-content bor-radius-10 mg-bo-10 pos-relative card-row add-row"
                                    >
                                        <mu-paper class="demo-paper" :zDepth="2" >

                                            <div class="card-01 card-storage" >

                                                <img src="../../../../static/img/add.png" alt="" @click="toChange">
                                            </div>

                                        </mu-paper>

                                    </div>
                                </div>
                            </waterfall-slot>
                            <!-- each component is wrapped by a waterfall slot -->
                            <waterfall-slot
                                    v-for="(item, index) in actItem"
                                    :width="250"
                                    :height="220"
                                    :order="index"
                                    :key="item.id"
                            >
                                <div>
                                    <v-billcomp
                                            :item="item"
                                            :index="index"
                                            class="item"
                                            :isGoods="isGoods"
                                            :currentRadio ="currentRadio"
                                            :isMutpart="isMutpart"
                                            :backSelectItems="selectItems"
                                            :backItems="getCurrentSelectItems"
                                            :isClose="isClose"
                                            :viewClick="function(){del(item)}"
                                            :isSelectBox="false"
                                    >
                                        <div class="text" style="margin-bottom: 0.5em">
                                            <h6 class="l1">{{item.goodsName}}</h6>
                                            <span class="l1"><span class="span1">单价</span>{{Number(item.price).toFixed(2)}}</span>
                                            <!--<span><span class="span2">会员价</span>{{ Number(item.memberPrize || 0).toFixed(2) }}</span>-->
                                            <span class="text-numspan">
                                                <div class="quantity-h">
                                                    <span>采购价</span>
                                                    <span v-show="!changeSure[index]">{{ item.purchasePrice }}</span>
                                                    <input type="number" class="text-number" :min="0" v-model="item.purchasePrice"
                                                           v-show="changeSure[index]">
                                                </div>
                                            </span>
                                            <span class="text-numspan">
                                                <div class="quantity-h">
                                                    <span>数&nbsp;&nbsp;&nbsp;&nbsp;量</span>
                                                    <span v-show="!changeSure[index]">{{ item.quantity }}</span>
                                                    <input type="number" class="text-number" :min="0" v-model="item.quantity"
                                                           v-show="changeSure[index]">
                                                </div>
                                            </span>
                                        </div>
                                        <div class="tr"  v-if="isNew">
                                            <span @click="changeNum(index,item,changeSure[index])" v-show="!changeSure[index]">修改</span>
                                            <span @click="saveNum(index,item,changeSure[index])"
                                                  v-show="changeSure[index]">确定</span>
                                        </div>
                                        <div v-if="!isNew">
                                            <span>&nbsp;</span>
                                        </div>
                                    </v-billcomp>
                                </div>
                            </waterfall-slot>

                        </waterfall>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script>
    import vSimpsearch from '../SimpSearch.vue';
    import * as type from '../../../store/types';
    import vBillcomp from '../../common/BillComp.vue';
    import Waterfall from '../../common/waterfall/Waterfall.vue';
    import WaterfallSlot from '../../common/waterfall/waterfall-slot';
    export default {
        components: {
            vSimpsearch,vBillcomp,Waterfall, WaterfallSlot
        },
        data: function () {
            return {
                loading: false,
                activeName: 'first',
                items: [],
                Actid: '',
                formInfo: {
                  kindCode: 10
                },
                formInfoRules: {},
                actItem: '',
                num: [0],
                purchaseNum:[0],
                changeSure: [],
                isGoods: true,
                currentRadio: {index:-1},
                selectItems: [],
                isMutpart:false,
                page: 1,
                totalPage: 1,
                quantity:0,
                selectGoods:'',
                isClose:false,
                selectDel:'',
                id: '',
                index: 0,
                itemInfo: {},
                isNew:false,
                options: [
                    {
                        value: '现购'
                    },
                    {
                        value: '赊购'
                    },
                ],
                value:"现购",
                isDisabled:false
            }
        },
        watch: {
            param(val){
                this.items = [];
                this.page = 1;
                this.totalPage = 1;
                this.loadMore();
            },
            value(){
                console.log(12)
                console.log()
                if(this.value=="赊购"){
                    this.formInfo.kind_code="20"
                }else{
                    this.formInfo.kind_code="10"
                }
            }
        },
        mounted: function () {
            console.log("=============>mounted")
            this.isClose = false;
            this.$$("#content").scrollTop(0)
            let self = this;
            this.$$("#content").on('scroll', function (e) {
                var scrollTop = self.$$("#content").scrollTop();
                var innerHeight = self.$$("#content").innerHeight();
                var scrollHeight = self.$$("#content").scrollHeight();
                if (scrollTop + innerHeight >= scrollHeight) {
                    self.page++;
                    if (self.page > self.totalPage) {
                        return;
                    }
                    self.loadMore();
                    console.log('*(******************' + self.page)
                }
            });

            document.getElementById("myDIV").addEventListener('wheel', function (e) {
                if (e.wheelDelta < 0 && self.$$("#content").scrollTop() === 0) {
                    console.log(e.wheelDelta < 0 && self.$$("#content").scrollTop() === 0)
                    self.page++;
                    self.loadMore();
                }
            });
        },
        activated: function () {
            this.$$("#content").scrollTop(0)
            let backInfo = this.$route.params;

            this.actItem='';
            this.num=[];
            this.isClose = true;
            this.isDisabled = false;
            this.page = 1;
            this.totalPage = 1;
            //从选择列表进入info
            if (backInfo.flag != undefined) {
                if (backInfo.flag == 'selectOrgan') {
                    console.log("==========>selectOrgan")
                    this.$set(this.formInfo, 'organName', backInfo.selected.name);
                    this.$set(this.formInfo, 'organId', backInfo.selected.id);
                    console.log(this.formInfo)
                }
                else if (backInfo.flag == 'selectHandler') {
                    console.log("==========>selectRoles")
                    this.$set(this.formInfo, 'handerName', backInfo.selected.name);
                    this.$set(this.formInfo, 'handerId', backInfo.selected.id);
                }
                else if (backInfo.flag == 'back') {
                    console.log("==========>back")
                }
                else {
                    return;
                }
                this.actItem =this.formInfo.actItem;
                this.isNew=false;
            }
            //新增
            else if (backInfo.new){
                this.activeName = 'first';
                this.isClose = true;
                this.formInfo = {
                  sn: '',
                  biztype: '',
                  organName: '',
                  handerName: '',
                  creator: '',
                  bizdate: '',
                  remark: '',
                  kindCode: '',
                  amount: ''
                };
                this.loading = true;
                let self = this;
                self.$axioxs.get('/sn/?key=sale')
                    .then(function (res) {
                        self.loading = false;
                        self.$set(self.formInfo,'sn',res.data);
                    })
                    .catch(function (error) {
                        console.log(error);
                        self.loading = false;
                        self.$message({
                            showClose: true,
                            type: 'error',
                            message: error
                        });

                    });
            }
            //修改
            else if (backInfo.item.id) {
              console.log(backInfo.item.state)
                if(backInfo.item.state == 2||backInfo.item.state == 1){
                  this.isClose = false;
                  this.isNew=false;
                  this.isDisabled = true;
                }
                else {
                  this.isClose = true;
                  this.isNew=true;
                  this.isDisabled = false;
                }
                this.activeName = 'first';
                this.Actid = this.$route.params.item.id;
                this.formInfo=this.$route.params.item;
                if(this.formInfo.kindCode==20){
                    this.value="赊购"
                }else{
                    this.value="现购"
                }
                this.actItem=this.$route.params.item.entries;
                if (backInfo.isBack) {
                    this.loadMore();
                    this.activeName = 'second';
                }
            }
            // 新增选择商品分录返回
            else if (backInfo.args) {
                this.isClose = true;
                this.isNew=false;
                this.activeName = 'second';
                this.actItem=backInfo.args;
                this.formInfo.actItem=this.actItem;
                this.$$(window).resize();
                for(var i=0;i<this.actItem.length;i++){
                    this.$set(this.changeSure, i, true);
                }

            }
            //
            else{
              this.isClose = false;
              this.isNew=false;
            }


        },
        methods: {
            loadMore() {
                console.log("==============>loadMore")
                console.log(this.totalPage)
                if (this.page <= this.totalPage) {
                    this.loading = true;
                    let self = this;
                    this.$axioxs.get('/purchase_bill/purchaseEntry?ownerId=' + this.formInfo.id)
                        .then(function (res) {
                          console.log()
                            self.totalPage = res.data.totalPage;
                            self.actItem = res.data.records;
                            self.actItem.forEach(item => {
                                self.items.push(item);
                            });
                            for(var i=0;i<self.actItem.length;i++){
                                self.$set(self.changeSure, i, false);
                            }
                            self.loading = false;
                        })
                        .catch(function (error) {
                            console.log(error);
                            self.$message({
                                showClose: true,
                                type: 'error',
                                message: error,
                                onClose:function () {
                                    self.loading = false;
                                }
                            });
                        });
                }
            },
            handleClick(tab, event) {
                if (this.activeName == 'first') {

                }
                else if (this.activeName == 'second') {
                    for(var i=0;i<this.actItem.length;i++){
                        this.$set(this.changeSure, i, true);
                    }
                    this.$$(window).resize();
                    this.page=1
                    this.totalPage=1;
                    if(this.formInfo.id){  //修改　点击tab标签
                        this.loadMore();
                    }else{

                    }
                }
            },
            info:function (item) {
                console.log(12)
            },

            del: function (item) {
                if(this.formInfo.id){
                    let self = this;
                    this.$axioxs.delete('/purchase_bill/purchase/' + item.id)
                        .then(function (res) {
                                console.log('删除成功')
                                self.$message({
                                    showClose: true,
                                    message: '删除成功',
                                    type: 'success'
                                });
                                self.actItem.splice(self.actItem.indexOf(item), 1)
                                self.activeName = "second";
                            },
                            (res) => {
                                this.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: res
                                });
                            });
                }else{
                    this.actItem.splice(this.actItem.indexOf(item), 1)
                }

            },
            changeNum: function (index, item, changeSure, toSure) {
                this.$set(this.changeSure, index, true);
                this.num[index] = item.quantity;
                this.purchaseNum[index] = item.purchasePrice;

            },
            getCurrentSelectItems: function (items) {
                console.log("==================>")
                console.log(items)
                this.selectDel = items;
            },
            saveNum: function (index, item, changeSure, toSure) {
                let self = this;
                this.$set(this.changeSure, index, false);
                var quantity = this.num[index];
                var purchaseNum = this.purchaseNum[index];
                let args = {
                    goods: {
                        id: item.goodsId
                    },
                    id: item.id,
                    quantity: item.quantity,
                    state: item.state,
                    purchasePrice:item.purchasePrice

                };
                if(quantity!=item.quantity ||purchaseNum!=item.purchasePrice){
                    this.$axioxs.post('/purchase_bill/updateEntry', args)
                        .then(function (res) {
                                self.loadMore();
                            },
                            (res) => {
                                this.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: res
                                });
                            }
                        )
                }

            },
            toChange:function () {
              this.$store.commit(type.CHANGE_INDEX, '/goodsComp');
              if(this.formInfo.id){
                  this.$router.push({
                      name: 'goodsB',
                      path: '/goodsComp',
                      params:{
                          'url':"/goods/on-shelf?kindCodes=10",
                          'saveurl':"/purchase_bill/saveEntry",
                          'backurl':"/purchaseInfo",
                          'item': this.formInfo,
                          'backName':"purchase",
                          'isDeliveryPage':'isDeliveryPage',
                          'isPurchase':'isPurchase'
                      },
                  });
              }else{
                  this.$router.push({
                      name: 'goodsB',
                      path: '/goodsComp',
                      params:{
                          'url':"/goods/on-shelf?kindCodes=10",
                          'backurl':"/purchaseInfo",
                          'item': this.formInfo,
                          'backName':"purchase",
                          'isDeliveryPage':'isDeliveryPage',
                          'actItem':this.actItem||[],
                          'isPurchase':'isPurchase'
                      },
                  });

              }

            },
            onSubmit: function (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let args = {
                            id: this.formInfo.id,
                            remark:this.formInfo.remark,
                            sn:this.formInfo.sn,
                            handerName:this.formInfo.handerName,
                            direction:1,
                            biztype:0,
                            kindCode:Number(this.formInfo.kind_code)||10
                        };
                        console.log(args)
                        var entryList =this.actItem;
                        console.log(entryList)
                        var arr=[];
                        for(var i=0;i<entryList.length;i++){
                            var objGood={};
                            objGood.goods={};
                            objGood.goods.id=entryList[i].id;
                            objGood.quantity =entryList[i].quantity;
                            objGood.purchasePrice =entryList[i].purchasePrice;
                            arr.push(objGood)
                        }
                        args.entries = arr;
                        let self = this;
                        if(this.formInfo.id){
                            let args = {
                                id: this.formInfo.id,
                                remark:this.formInfo.remark,
                                handerName:this.formInfo.handerName,
                                kindCode:Number(this.formInfo.kind_code)||this.formInfo.kindCode
                            };
                            this.$axioxs.post("/purchase_bill/updateBill/", args)
                                .then(function (res) {
                                        self.back();
                                    },
                                    (res) => {
                                        self.$message({
                                            showClose: true,
                                            type: 'error',
                                            message: res
                                        });
                                    });
                        }else{
                            if(args.entries.length<1){
                                self.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: '请至少选择一种商品'
                                });
                            }else {
                                this.$axioxs.post("/purchase_bill/save", args)
                                    .then(function (res) {
                                            console.log(res)
                                            self.back();
                                            self.loadMore();
                                            console.log(self.formInfo)
                                        },
                                        (res) => {
                                            this.$message({
                                                showClose: true,
                                                type: 'error',
                                                message: res
                                            });
                                        });
                            }

                        }

                    }
                });
            },
            effect: function () {
              console.log("==================>effect");
              if(this.formInfo.state == 0){
                this.loading = true;
                let self = this;
                this.$axioxs.post("/purchase_bill/pay/"+ this.formInfo.id)
                  .then(function (res) {
                        console.log(res);
                        self.loading = false;

                        self.back();
                    },
                    (res) => {
                        self.$message({
                            showClose: true,
                            type: 'error',
                            message: res
                        });
                    });
              }
              else {
                // this.onSubmit("formInfo");
                this.$message({
                    showClose: true,
                    type: 'warning',
                    message: "请先保存！"
                });
              }
            },
            back: function () {
                this.$store.commit(type.CHANGE_INDEX, '/purchase');
                this.$router.push({
                    name: '',
                    path: '/purchase',
                });
            }
        }
    }
</script>

<style scoped>


    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .close-del {
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
    }

    .close-fa-circle {
        font-size: 1.25em;
    }
    .member-info-title {
        padding-top: 60px;
    }

    .member-info-form {
        width: 90%;
        padding-top: 0px;
        margin: 0 auto;
    }

    .img {
        width: 80px;
        height: 80px;
        margin: 10px auto;
    }
    .item {
        position: absolute;
        top: 5px;
        left: 5px;
        right: 5px;
        bottom: 5px;
        font-size: 1.2em;
        color: rgb(0, 158, 107);
    }
    .text {
        margin-bottom: 1em;
    }

    .text h6 {
        margin-bottom: 5px;
    }

    .span1 {
        background-color: #3eb3f9;
        border-radius: 20px;
        padding: 2px 5px;
        color: #fff !important;
        font-size: .6em !important;
        margin-right: 3px;
    }

    .span2 {
        background-color: #6699ff;
        border-radius: 20px;
        padding: 2px 5px;
        color: #fff !important;
        font-size: .6em;
        margin-right: 3px;
    }

    .remark {
        padding: 3px 0;
    }
    .text-number{
        width: 50%;
        height: 27px;
        border: 1px solid #cacaca;
        border-radius: 3px;
    }
    .text-numspan{
        display: block;
    }
    .quantity-h{
        height:30px;
        line-height: 30px;
    }
    .card-storage{
        height:210px;
        position:relative;
        z-index:2;
        padding:4em 0;
    }
    .add-row{
      margin: 5px;
    }
</style>
